<script>

import {login, emailLogin, setAccessToken, getAccessToken, setUserInfo, tokenLogin, setRole, sendEmailCode} from '../services/user'

function emailHasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}

export default {
  name: 'Login',
  data () {
    return {
      emailHasErrors,
      ispwdLogin:true,
      showPage: false,
      logging: false,
      codeBtnWord: "获取验证码",
      waitTime: 61, // 获取验证码按钮失效时间
      error: '',
      form: this.$form.createForm(this),
      emailform: this.$form.createForm(this)
    }
  },
  mounted() {
    this.$nextTick(() => {
      // To disabled button at the beginning.
      this.emailform.validateFields(['email']);
    });
  },
  // computed: {
  //   //用于校验手机号码格式是否正确
  //   emailStyle() {
  //     let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
  //     console.log(this.emailform.getFieldValue('email'))
  //     if (!reg.test(this.emailform.getFieldValue('email'))) {
  //       console.log('邮箱格式不对')
  //       return false;
  //     }
  //     console.log('邮箱格式正确对')
  //     return true;
  //   },

  //   // 控制获取验证码按钮是否可点击
  //   getCodeBtnDisable: {
  //     //设置按钮61s
  //     get() {
  //       if (this.waitTime === 61) {
  //         if (this.emailform.getFieldValue('email')!= "" && this.emailStyle) {
  //           return false;
  //         }
  //       }
  //       return true;
  //     },
  //     // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
  //     set() {}
  //   },
  // },
  methods: {
    // Only show error after a field is touched.
    emailError() {
      const { getFieldError, isFieldTouched } = this.emailform;
      return isFieldTouched('email') && getFieldError('email');
    },
    // 获取验证码
    getCode() {
      this.waitTime--;
      this.getCodeBtnDisable = true;
      this.codeBtnWord = `${this.waitTime}s 后获取`;
      const email = this.emailform.getFieldValue('email')
      sendEmailCode(email)
            .then(res => res.json())
            .catch(err => {
              console.log(err);
            })
      let timer = setInterval(() => {
        if (this.waitTime > 1) {
          this.waitTime--;
          this.codeBtnWord = `${this.waitTime}s 后获取`;
        } else {
          clearInterval(timer);
          this.codeBtnWord = "获取验证码";
          this.getCodeBtnDisable = false;
          this.waitTime = 61;
        }
      }, 1000);
    },
    onSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          const account = this.form.getFieldValue('account')
          const password = this.form.getFieldValue('password')
          login(account, password)
            .then(res => res.json())
            .then(this.afterLogin)
            .catch(err => {
              console.log(err);
            })
        }
      })
    },
    onEmailSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          const email = this.emailform.getFieldValue('email')
          const emailcode = this.emailform.getFieldValue('emailcode')
          emailLogin(email, emailcode)
            .then(res => res.json())
            .then(this.afterLogin)
            .catch(err => {
              console.log(err);
            })
        }
      })
    },
    afterLogin(res) {
      this.logging = false
      this.$store.commit('setRole', "user");
      const loginRes = res
      const {data, code, msg} = loginRes;
      if (code == 0) {
        setAccessToken(data);
        setRole("user");
        this.$message.success("Login successfully, redirecting...", 1);
        console.log("token", getAccessToken());
        this.$global.IS_LOGIN = true;
        setTimeout(() => {
          this.$router.go('/')
        }, 500)
        // let that = this;
        // tokenLogin()
        //   .then(res => res.json())
        //   .then(res => {
        //     const {data, code, msg} = res;
        //     if(code == 0 || code == '0'){
        //       setUserInfo(data);
        //       that.$router.push('/');
        //     }
        //   })
      } else {
        this.error = msg;
      }
    },
  },
  created(){
    let that = this;
    tokenLogin()
      .then(res => res.json())
      .then(res => {
        const {data, code, msg} = res;
        if(code == 0 || code == '0'){
          setUserInfo(data);
          that.$router.push('/');
        }else{
          that.showPage = true;
        }
      })
      .catch(error => {
        that.showPage = true;
      })
  }
}
</script>

<template>
  <div v-show="showPage">
    <div class = "top">
      <div class="desc">SECT G3 Library Management System</div>
    </div>
    <div class="login">
      <!-- 两个a-formb并列根据属性值控制显示 -->

      <!-- pwd login form -->
      <a-form @submit="onSubmit" :form="form" v-if="ispwdLogin">
            <a-alert type="error" :closable="true" v-show="error" :message="error" showIcon style="margin-bottom: 24px;" />
            <a-form-item>
              <a-input
                autocomplete="autocomplete"
                size="large"
                placeholder="Please input your id"
                v-decorator="['account', {rules: [{ required: true, message: 'Please input your id', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                size="large"
                placeholder="Please input your password"
                autocomplete="autocomplete"
                type="password"
                v-decorator="['password', {rules: [{ required: true, message: 'Please input your password', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="lock" />
              </a-input>
            </a-form-item>
          <!-- <div>
            <a-checkbox :checked="true" >自动登录</a-checkbox>
          </div> -->
          <a-form-item>
            <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit" type="primary">LOGIN</a-button>
          </a-form-item>
          <a-divider>其他登录方式</a-divider>
          <a-form-model-item style="text-align: center">
              <a-space size="large">
                  <a-icon type="mail" @click="ispwdLogin = false" style="font-size: 2em;cursor: pointer;color:#f50"/>
              </a-space>
          </a-form-model-item>

          <div>
            <router-link style="float: right" to="/register" >REGISTER</router-link>
            <router-link style="float: left" to="/admin/login" >ADMIN LOGIN</router-link>
          </div>
      </a-form>


      <!-- email login form -->
      <a-form :form="emailform" @submit="onEmailSubmit"  v-else>
            <a-alert type="error" :closable="true" v-show="error" :message="error" showIcon style="margin-bottom: 24px;" />
            <a-form-item :validate-status="emailError() ? 'error' : ''" :help="emailError() || ''">
              <a-input
                autocomplete="autocomplete"
                size="large"
                placeholder="Please input your email"
                v-decorator="['email', {rules: [{ required: true, message: 'Please input your email', pattern:/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/, whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="mail" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                size="large"
                style="width: 69.5%"
                :maxLength="6"
                placeholder="Please input verification code"
                autocomplete="autocomplete"
                v-decorator="['emailcode', {rules: [{ required: true, message: 'Please input verification code', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="key" />
              </a-input>
              <a-button
                size="large"
                class="btnCode"
                :disabled="emailHasErrors(emailform.getFieldsError(['email']))"
                @click="getCode()"
              >
              {{ codeBtnWord }}
              </a-button>
            </a-form-item>
        <!-- <div>
          <a-checkbox :checked="true" >自动登录</a-checkbox>
        </div> -->
        <a-form-item>
          <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit" type="primary">LOGIN</a-button>
        </a-form-item>
        <div>
          <router-link style="float: right" to="/register" >REGISTER</router-link>
          <router-link style="float: left" to="/admin/login" >ADMIN LOGIN</router-link>
        </div>
      </a-form>
    </div>
  </div>
</template>


<style>
  .top {
    text-align: center;
    height: 20vh;
  }
  .desc {
    font-size: 40px;
    color: black;
    margin-top: 40px;
    margin-bottom: 40px;
  }
  .header {
    height: 44px;
    line-height: 44px;
  }
  .header a {
    text-decoration: none;
  }
  .logo {
    height: 44px;
    vertical-align: top;
    margin-right: 16px;
  }
  .title {
    font-size: 33px;
    color: red;
    font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
    font-weight: 600;
    position: relative;
    top: 2px;
  }
  .login{
    width: 368px;
    margin: 0 auto;
    height: 50vh;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button{
        font-size: 14px;
      }
    }
  }
  .icon {
    font-size: 24px;
    color: gray;
    margin-left: 16px;
    vertical-align: middle;
    cursor: pointer;
    transition: color 0.3s;
  }
</style>
